﻿using EnterpriseDT.Net.Ftp;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;

namespace FTPClientTest
{
    public partial class Form1 : Form
    {


        public Form1()
        {
            InitializeComponent();



            //DirectoryInfo TheFolder = new DirectoryInfo(@"C:\Users\周杨\Desktop\FTPClient\FTPClient\bin\Debug");
            //foreach (DirectoryInfo NextFolder in TheFolder.GetDirectories())
            //    //this.treeView1.Items.Add(NextFolder.Name);
            //this.treeView1.Nodes.Add(NextFolder.Name);
            //DirectoryInfo theFolder = new DirectoryInfo(@"C:\Users\周杨\Desktop\FTPClient\FTPClient\bin\Debug");
            // DirectoryInfo[] dirInfo = theFolder.GetDirectories();
            //SearchTreeNode(dirInfo, this.treeView1.Nodes);
            //遍历文件夹

            //foreach (DirectoryInfo NextFolder in dirInfo)
            //{
            //    //DirectoryInfo[] dirInfo = NextFolder.GetDirectories();
            //    // this.listBox1.Items.Add(NextFolder.Name);
            //    //FileInfo[] fileInfo = NextFolder.GetFiles();
            //    //foreach (FileInfo NextFile in fileInfo)
            //    //{//遍历文件
            //        TreeNode tn = new TreeNode(NextFolder.Name);
            //        this.treeView1.Nodes.Add(tn);
            //    //}            
            //}





        }

        //public void SearchTreeNode(DirectoryInfo[] dirInfo,TreeNodeCollection tnc)
        //{
        //    foreach (DirectoryInfo NextFolder in dirInfo)
        //    {
        //        TreeNode tn = new TreeNode(NextFolder.Name);
        //        tnc.Add(tn);
        //        SearchTreeNode(NextFolder.GetDirectories(),tnc);

        //    }
        //}
        //private void LoadDataToTree(TreeNodeCollection treeNode, TreeNodeCollection list)
        //{
        //    foreach (TreeNodeCollection arr in list)
        //    {
        //        TreeNode tree = treeNode.Add(arr.);
        //        tree.Tag = arr.AreaId;
        //        LoadDataToTree(tree.Nodes, bll.GetTblAreaListByID(arr.AreaId)); //递归循环
        //    }
        //}





































        //ftp://172.168.10.180/media/


        //private const string ftpServerIP = "172.168.10.180";
        //private const string ftpRemotePath = "media";
        //private const string ftpUserID = "xw";
        //private const string ftpPassword = "xw";


        private const string ftpServerIP = "ftp.hp.cr";
        private const string ftpRemotePath = "Project";
        private const string ftpUserID = "hpwg01";
        private const string ftpPassword = "hp112358ftp";





        string filePath = @"C:\Users\周杨\Desktop\FTPClient";
        string filename = "123.txt";
        // string ftpServerIP = "127.0.0.1";
        string ftpUserIDb = "home";
        // string ftpPassword = "123456";

        private void button1_Click(object sender, EventArgs e)
        {

            UploadFtp(filePath, filename, ftpServerIP, ftpUserIDb, ftpPassword);

        }





        public static int UploadFtp(string filePath, string filename, string ftpServerIP, string ftpUserID, string ftpPassword)
        {
            FileInfo fileInf = new FileInfo(filePath + "\\" + filename);
            string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
            FtpWebRequest reqFTP;
            // Create FtpWebRequest object from the Uri provided 
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileInf.Name));
            try
            {
                // Provide the WebPermission Credintials 
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

                // By default KeepAlive is true, where the control connection is not closed 
                // after a command is executed. 
                reqFTP.KeepAlive = false;

                // Specify the command to be executed. 
                reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

                // Specify the data transfer type. 
                reqFTP.UseBinary = true;

                // Notify the server about the size of the uploaded file 
                reqFTP.ContentLength = fileInf.Length;

                // The buffer size is set to 2kb 
                int buffLength = 2048;
                byte[] buff = new byte[buffLength];
                int contentLen;

                // Opens a file stream (System.IO.FileStream) to read the file to be uploaded 
                //FileStream fs = fileInf.OpenRead(); 
                FileStream fs = fileInf.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                // Stream to which the file to be upload is written 
                Stream strm = reqFTP.GetRequestStream();

                // Read from the file stream 2kb at a time 
                contentLen = fs.Read(buff, 0, buffLength);

                // Till Stream content ends 
                while (contentLen != 0)
                {
                    // Write Content from the file stream to the FTP Upload Stream 
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }

                // Close the file stream and the Request Stream 
                strm.Close();
                fs.Close();
                return 0;
            }
            catch (Exception ex)
            {
                reqFTP.Abort();
                //  Logging.WriteError(ex.Message + ex.StackTrace);
                return -2;
            }
        }

        /// <summary>
        /// ftp方式下载 
        /// </summary>
        public static int DownloadFtp(string filePath, string fileName, string ftpServerIP, string ftpUserID, string ftpPassword)
        {
            FtpWebRequest reqFTP;
            try
            {
                //filePath = < <The full path where the file is to be created.>>, 
                //fileName = < <Name of the file to be created(Need not be the name of the file on FTP server).>> 
                FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);

                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileName));
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                reqFTP.KeepAlive = false;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                long cl = response.ContentLength;
                int bufferSize = 2048;
                int readCount;
                byte[] buffer = new byte[bufferSize];

                readCount = ftpStream.Read(buffer, 0, bufferSize);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }

                ftpStream.Close();
                outputStream.Close();
                response.Close();
                return 0;
            }
            catch (Exception ex)
            {
                // Logging.WriteError(ex.Message + ex.StackTrace);
                // System.Windows.Forms.MessageBox.Show(ex.Message);
                return -2;
            }
        }



        private void button2_Click(object sender, EventArgs e)
        {
            listView1.Items.Clear();
            richTextBox1.Clear();

            using (var conn = new FTPConnection
            {
                ServerAddress = ftpServerIP,
                ServerDirectory = ftpRemotePath,
                UserName = ftpUserID,
                Password = ftpPassword,
                CommandEncoding = Encoding.GetEncoding("GBK")
            })
            {
                conn.Connect();

                //创建目录L11  
                //
                if (!conn.DirectoryExists(@"\project\01"))
                {
                    conn.CreateDirectory(@"\project\01");
                }

                //============切换当前工作目录到L11============  
                conn.ChangeWorkingDirectory(@"\project\01");
                //上行代码也可以用conn.ServerDirectory = "L11";  

                //上传"文档.txt"  
                conn.UploadFile("123.txt", "123.txt");



                button3_Click(sender, e);
                ////创建子目录L21,L22  
                //conn.CreateDirectory("L21");
                //conn.CreateDirectory("L22");

                ////在当前工作目录L11上传文件"L11.htm"  
                //conn.UploadFile("11.htm", "11.htm");

                ////============切换当前工作目录到L21============  
                //conn.ChangeWorkingDirectory("L21");

                ////上传文件21.htm  
                //conn.UploadFile("21.htm", "21.htm");
                ////创建目录L31  
                //conn.CreateDirectory("L31");

                ////============切换当前工作目录到L31============  
                //conn.ChangeWorkingDirectory("L31");

                ////上传文件31.htm  
                //conn.UploadFile("31.htm", "31.htm");
            }
        }



        private void btnCreateAndUpload_Click(object sender, EventArgs e)
        {

        }

        private void button4_Click(object sender, EventArgs e)
        {
            listView1.Items.Clear();
            richTextBox1.Clear();
            string filepath1 = null;
            string filename1 = null;
            OpenFileDialog opd = new OpenFileDialog();
            if (opd.ShowDialog() == DialogResult.OK)
            {
                filepath1 = opd.FileName;
                filename1 = opd.SafeFileName;
            }




            using (var conn = new FTPConnection
            {
                ServerAddress = ftpServerIP,
                ServerDirectory = ftpRemotePath,
                UserName = ftpUserID,
                Password = ftpPassword,
                CommandEncoding = Encoding.GetEncoding("GBK")
            })
            {
                conn.Connect();


                //传入项目ID
                if (!conn.DirectoryExists(@"\project\02"))
                {
                    conn.CreateDirectory(@"\project\02");
                }

                //============切换当前工作目录到L11============  
                conn.ChangeWorkingDirectory(@"\project\02");
                //上行代码也可以用conn.ServerDirectory = "L11";  

                //上传"文档.txt"  
                conn.UploadFile(filepath1, filename1);





                //获取指定目录的所有子目录和文件信息  
                conn.ChangeWorkingDirectory(@"\Project\02\");
                var files1 = conn.GetFileInfos();
                ShowFileInfos(files1);

                this.listView1.BeginUpdate();
                foreach (var item in files1)
                {
                    if (item.Name == "." || item.Name == "..")
                    {
                        continue;
                    }

                    ListViewItem lvi = new ListViewItem();
                    lvi.Text = item.Name;
                    lvi.SubItems.Add(item.Size.ToString() + "字节");
                    lvi.SubItems.Add(item.LastModified.ToString());
                    this.listView1.Items.Add(lvi);
                }

                this.listView1.EndUpdate();



            }
        }


        private void button3_Click(object sender, EventArgs e)
        {
            using (var conn = new FTPConnection
            {
                ServerAddress = ftpServerIP,
                ServerDirectory = ftpRemotePath,
                UserName = ftpUserID,
                Password = ftpPassword,
                CommandEncoding = Encoding.GetEncoding("GBK")
            })
            {
                conn.Connect();
                //获取指定目录的所有子目录和文件信息  
                conn.ChangeWorkingDirectory(@"/Project/02/");
                var files1 = conn.GetFileInfos();
                ShowFileInfos(files1);

                this.listView1.BeginUpdate();
                foreach (var item in files1)
                {
                    if (item.Name == "." || item.Name == "..")
                    {
                        continue;
                    }

                    ListViewItem lvi = new ListViewItem();
                    lvi.Text = item.Name;

                    lvi.SubItems.Add(item.Size.ToString() + "字节");
                    lvi.SubItems.Add(item.LastModified.ToString());
                    lvi.Tag = item.Path;
                    this.listView1.Items.Add(lvi);
                }

                this.listView1.EndUpdate();


                /*结果如下： 
                 File, /web/L11/L21/21.htm, 21.htm, 11.2KB, 2013-9-26 14:51:00 
                 Dir, /web/L11/L21/L31, L31, 0KB, 2013-9-26 14:51:00 
                 */

                ////返回上级目录，例子中为web/L11  
                //conn.ChangeWorkingDirectoryUp();
                //var files2 = conn.GetFileInfosRecursive();
                //ShowFileInfos(files2);
                /*结果如下： 
                File, /web/L11/11.htm, 11.htm, 59.4KB, 2013-9-26 14:51:00 
                Dir, /web/L11/L21, L21, 0KB, 2013-9-26 14:51:00 
                Dir, /web/L11/L22, L22, 0KB, 2013-9-26 14:51:00 
                File, /web/L11/文档.txt, 文档.txt, 40.8KB, 2013-9-26 14:51:00 
                File, /web/L11/L21/21.htm, 21.htm, 11.2KB, 2013-9-26 14:51:00 
                Dir, /web/L11/L21/L31, L31, 0KB, 2013-9-26 14:51:00 
                File, /web/L11/L21/L31/31.htm, 31.htm, 5.6KB, 2013-9-26 14:51:00 
                 */
            }



            //this.listView1.BeginUpdate();   //数据更新，UI暂时挂起，直到EndUpdate绘制控件，可以有效避免闪烁并大大提高加载速度 

            //for (int i = 0; i < 10; i++)   //添加10行数据 
            //{
            //    ListViewItem lvi = new ListViewItem();

            //    lvi.ImageIndex = i;     //通过与imageList绑定，显示imageList中第i项图标 

            //    lvi.Text = "subitem" + i;

            //    lvi.SubItems.Add("第2列,第" + i + "行");

            //    lvi.SubItems.Add("第3列,第" + i + "行");

            //    this.listView1.Items.Add(lvi);
            //}

            //this.listView1.EndUpdate();

















        }











        void ShowFileInfos(FTPFile[] files)
        {
            foreach (var file in files)
            {
                string info = string.Format("{0}, {1}, {2}, {3}KB, {4}",
                    file.Dir ? "Dir" : "File", file.Path, file.Name, Math.Round(file.Size / 1024.0, 1), file.LastModified);
                richTextBox1.AppendText(info + "\r\n");
            }
            richTextBox1.AppendText("\r\n");
        }


        private void btnDelete_Click(object sender, EventArgs e)
        {
            using (var conn = new FTPConnection
            {
                ServerAddress = ftpServerIP,
                ServerDirectory = ftpRemotePath,
                UserName = ftpUserID,
                Password = ftpPassword,
                CommandEncoding = Encoding.GetEncoding("GBK")
            })
            {
                conn.Connect();
                //递归删除目录及所有子目录和文件  
                conn.DeleteDirectoryRecursive("L11");
                //如果删除单个文件，路径为当前目录的相对路径  
                //conn.DeleteFile("L11/11.htm");  
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            string localpath = null;

            string remotepath = this.listView1.SelectedItems[0].Tag.ToString();
            string localfilename = this.listView1.SelectedItems[0].Text.ToString();

            SaveFileDialog sfd = new SaveFileDialog();

            sfd.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            sfd.FilterIndex = 2;
            sfd.RestoreDirectory = true;
            sfd.FileName = localfilename;
            //sfd.Filter = "All files (*.*)";
            //sfd.AddExtension = true;
            if (sfd.ShowDialog() == DialogResult.OK)
            {

                using (var conn = new FTPConnection
                {
                    ServerAddress = ftpServerIP,
                    ServerDirectory = ftpRemotePath,
                    UserName = ftpUserID,
                    Password = ftpPassword,
                    CommandEncoding = Encoding.GetEncoding("GBK")
                })
                {
                    conn.Connect();
                    conn.DownloadFile(sfd.FileName, remotepath);
                    
                }
            }
        }
    }
    public static class FtpClientExtensions
    {
        /// <summary>  
        /// 递归获取目录的所有子目录和文件信息  
        /// </summary>  
        public static FTPFile[] GetFileInfosRecursive(this FTPConnection conn)
        {
            var resultList = new List<FTPFile>();
            var fileInfos = conn.GetFileInfos();
            resultList.AddRange(fileInfos);
            foreach (var fileInfo in fileInfos)
            {
                if (fileInfo.Dir)
                {
                    conn.ServerDirectory = fileInfo.Path;
                    resultList.AddRange(conn.GetFileInfosRecursive());
                }
            }
            return resultList.ToArray();
        }
        /// <summary>  
        /// 递归删除目录(包括所有子目录和文件信息)  
        /// </summary>  
        public static void DeleteDirectoryRecursive(this FTPConnection conn, string directoryName)
        {
            conn.ChangeWorkingDirectory(directoryName);
            var fileInfos = conn.GetFileInfos();
            foreach (var fileInfo in fileInfos)
            {
                if (fileInfo.Dir)
                    conn.DeleteDirectoryRecursive(fileInfo.Name);
                else
                    conn.DeleteFile(fileInfo.Name);
            }
            conn.ChangeWorkingDirectoryUp();
            conn.DeleteDirectory(directoryName);
        }



    }

}
